package com.mooc.lib_network

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 单例模式封装retrofit框架
 * 私有化构造器
 * 添加伴生对象
 * */
class RetrofitSingle private constructor(){

    companion object{
        val retrofitSingle : RetrofitSingle by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            RetrofitSingle()
        }
        @Synchronized
        fun instance(): RetrofitSingle {
            return retrofitSingle
        }
    }

    private var retrofit : Retrofit?=null

    fun getRetrofit():Retrofit{
        if (retrofit == null)
            createRetrofit()
        return retrofit!!
    }

    fun createRetrofit(){

        val okBuilder = OkHttpClient.Builder()
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        okBuilder.addInterceptor(loggingInterceptor)
            .connectTimeout(1,TimeUnit.MINUTES)
            .readTimeout(1,TimeUnit.MINUTES)
            .writeTimeout(1,TimeUnit.MINUTES)
        val builder = Retrofit.Builder()
        builder.client(okBuilder.build())
            .baseUrl(ApiConst.BASEURL)
            .addConverterFactory(GsonConverterFactory.create())
        retrofit = builder.build()
    }

}